<?php
/**
 * Created by PhpStorm.
 * User: yann
 * Date: 2019/5/8
 * Time: 下午9:55
 */

namespace App\Http\Controllers\Admin;


use App\Models\Attach;
use App\Models\AttachType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use zgldh\QiniuStorage\QiniuStorage;

class UploadController extends BaseController
{
    public function __construct(Request $request, Attach $attach)
    {
        $this->request = $request;
        $this->attach = $attach;
    }

    public function index()
    {
        $page = $this->request->get('page',1);
        $size = $this->request->get('size',20);
        $type = $this->request->get('type',0);
        $query = $this->attach->where('type',$type);
        $count = $query->count();

        $list = $query->offset(($page - 1)* $size)->limit($size)->get()->toArray();
        $return = [
            'list' => $list,
            'count' => $count
        ];
        return $this->buildSuccess($return);
    }

    public function store()
    {
        $file = $this->request->file('file');
        $typeId = $this->request->get('typeId',0);

        // 文件是否上传成功
        if ($file->isValid()) {

            // 获取文件相关信息
            $originalName = $file->getClientOriginalName(); // 文件原名
            $ext = $file->getClientOriginalExtension();     // 扩展名
            $realPath = $file->getRealPath();   //临时文件的绝对路径
            $type = $file->getClientMimeType();     // image/jpeg
            // 上传文件
            $filename = uniqid();
            // 使用我们新建的uploads本地存储空间（目录）
            //这里的uploads是配置文件的名称
            $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));

            if($bool){
                $res = $attach = Attach::create([
                    'type' => $typeId,
                    'name' => $filename,
                    'save_type' => Attach::LOCALTYPE,
                    'ext' => $ext,
                    'size' => $file->getSize(),
                    'path' => './uploads/'.$filename,
                    'create_time' => time()
                ]);

                if($res){
                    return $this->buildSuccess('./uploads/'.$filename,'上传成功');
                }else{
                    return $this->buildError(0,'上传失败');
                }
            }else{
                return $this->buildError(0,'上传失败');
            }
        }

    }

    public function destroy()
    {
        $ids = $this->request->get('ids');
        $ids = json_decode($ids,true);
        $list = Attach::whereIn('id',$ids)->get()->toArray();
        $qiniu = QiniuStorage::disk('qiniu');

        foreach ($list as $key => $value){
            if($value['save_type'] == 1 && file_exists($value['path'])){
                unlink($value['path']);
            }else{
                $qiniu->delete($value['path']);
            }
        }
        Attach::destroy($ids);
        return $this->buildSuccess($list);

    }

    /**
     * 判断是否开启七牛，获取七牛token
     * @return false|string
     */
    public function getQiniuToken(){
        if(env('IS_QINIU')){
            $qiniu = QiniuStorage::disk('qiniu');
            $token = $qiniu->uploadToken();
            if($token){
                return $this->buildSuccess([
                    'token' => $token,
                    'isQiNiu' => 1,
                    'action' => '//up-z2.qiniup.com/'
                ]);
            }else{
                return $this->buildSuccess([
                    'isQiNiu' => 0
                ]);
            }
        }else{
            return $this->buildSuccess(['isQiNiu'=>0]);
        }
    }

    /**
     * 保存七牛上传后的key
     * @return false|string
     */
    public function qiniuStore(){
        $key = $this->request->get('key','');
        $type = $this->request->get('type',0);
        if(!$key)
            return $this->buildError(-1,'参数错误');

        $attach = Attach::create([
            'type' => $type,
            'name' => $key,
            'save_type' => Attach::QINIUTYPE,
            'path' => ''.$key,
        ]);
        return $this->buildSuccess($attach['path']);
    }

    public function attachType()
    {
        $list = AttachType::get()->toArray();
        return $this->buildSuccess($list);
    }

    public function typeStore()
    {
        $data = $this->request->all();
        $model = AttachType::create($data);
        if($model){
            return $this->buildSuccess($model);
        }else{
            return $this->buildError();
        }
    }

    public function typeUpdate($id)
    {
        $model = AttachType::findOrFail($id);
        $data = $this->request->all();
        if($model->update($data)){
            return $this->buildSuccess($model);
        }else{
            return $this->buildError();
        }
    }

    public function typeDestroy($id)
    {
        $model = AttachType::findOrFail($id);
        Db::beginTransaction();
        try{
            $model->delete();
            $this->attach->where('type',$model->id)->update(['type'=>0]);
            Db::commit();
            return $this->buildSuccess();
        } catch (\Exception $e){
            Db::rollBack();
            return $this->buildError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 批量移动图片到其他分类
     * @return false|string
     */
    public function moveAttachToType(){
        $typeId = $this->request->get('typeId',0);
        $id = $this->request->get('id');
        $id = json_decode($id,true);
        Attach::whereIn('id',$id)->update(['type'=>$typeId]);
        return $this->buildSuccess([]);
    }
}
